package com.brillilab.common.rocketmq;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Configuration;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.Producer;
import com.aliyun.openservices.ons.api.SendResult;

/**
 * 消息生产者
 * @author lj
 *
 */
@Configuration
public class OnsProducer {
	
	@Autowired
	private OnsProperties onsProperties;
	
	/**
	 * 生产者
	 */
	@Autowired
    @Qualifier("onsMessageProducer")
    private Producer onsMessageProducer;


	/**
	 * 集群消息发送
	 * @param topic 消息主题
	 * @param mqVo 消息对象
	 * @return
	 */
	public SendResult sendClusteringMessage(String topic, OnsMessageVo mqVo) {
		Message msg = new Message(topic, onsProperties.clusteringTag, JSONObject.toJSONString(mqVo).getBytes());
		msg.setKey(mqVo.getType() + "_" + mqVo.getMessageId());
		return onsMessageProducer.send(msg);
	}

	/**
	 * 广播订阅消息发送
	 * @param topic 消息主题
	 * @param mqVo 消息对象
	 * @return
	 */
	public SendResult sendBroadcastMessage(String topic, OnsMessageVo mqVo) {
		Message msg = new Message(topic, onsProperties.broadcastTag, JSONObject.toJSONString(mqVo).getBytes());
		//key值改为type+messageId，便于以后处理消息做幂等处理
		msg.setKey(mqVo.getType() + "_" + mqVo.getMessageId());
		return onsMessageProducer.send(msg);
	}

	public OnsProperties getOnsProperties() {
		return onsProperties;
	}

	/**
	 * @Description: 集群用户访问记录发送
	 * @Param [topic, mqVo]
	 */
	public SendResult sendClusteringUserLog(UserLogVo userLogVo) {
		Message msg = new Message(onsProperties.userLogTopic, onsProperties.clusteringTag, JSONObject.toJSONString(userLogVo).getBytes());
		return onsMessageProducer.send(msg);
	}
}
